<?php
/**
 *
 * (model)
 */
namespace App\Models\SalesReport;

use App\Models\Basics\AmazonAccount;
use App\Models\Basics\RakutenAccount;
use App\Models\Basics\ShopifyAccount;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysPlat;
use Illuminate\Database\Eloquent\Model;
class MonthlySa extends Model
{
    protected $table = 'sr_monthly_sa';

    protected $guarded = [];

    public $timestamps = false;

    const V_NUM = 15;

    public function amazon_account(){
        return $this->belongsTo(AmazonAccount::class,'account_id');
    }
    public function shopify_account(){
        return $this->belongsTo(ShopifyAccount::class,'account_id');
    }
    public function rakuten_account(){
        return $this->belongsTo(RakutenAccount::class,'account_id');
    }

    public function area(){
        return $this->belongsTo(SysArea::class,'area_id');
    }

    public function country(){
        return $this->belongsTo(SysCountry::class,'country_id');
    }

    public function plat(){
        return $this->belongsTo(SysPlat::class,'plat_id','plat_id');
    }

    public static function headersField(){
        $fields = [];
        $fields['account'] = ['title' => '账号','sumField' => false];
        $fields['plat'] = ['title' => '平台','sumField' => false];
        $fields['area'] = ['title' => '站点','sumField' => false];
        $fields['country'] = ['title' => '国家','sumField' => false];
        for($i = self::V_NUM - 1; $i >= 0; $i--){
            $fields['month'.$i] = [
                'title' => date("Y.m",strtotime(date('Y-m-01') . "-$i month")),
                'sumField' => true
            ];
        }
        return $fields;
    }

    public static function getDownloadData($re){
        foreach ($re as $item){
            $temp = [];
            $temp['account'] = '';
            if ($item->plat_id == SysPlat::PLAT_AMAZON) {
                $temp['account'] = $item->amazon_account->account ?? '';
            }
            if ($item->plat_id == SysPlat::PLAT_SHOPIFY) {
                $temp['account'] = $item->shopify_account->account ?? '';
            }
            if ($item->plat_id == SysPlat::PLAT_RAKUTEN) {
                $temp['account'] = $item->rakuten_account->account ?? '';
            }
            $temp['plat'] = $item->plat->title ?? '';
            $temp['area'] = $item->area->area ?? '';
            $temp['country'] = $item->country->country ?? '';
            for($i = self::V_NUM - 1; $i >= 0; $i--){
                $temp['month'.$i] = $item->{'month'.$i};
            }
            yield $temp;
        }
    }
}
